package com.bg.repo.impl;

import com.bg.api.MongDataPageable;
import com.bg.data.Persion;
import com.bg.repo.PersionRepoTemp;
import com.mongodb.WriteResult;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

@Service("PersionRepoTempImpl")
public class PersionRepoTempImpl implements PersionRepoTemp {

    @Resource
    MongoTemplate mongoTemplate;

    @Override
    public void insertBase(Persion persion) {
        mongoTemplate.insert(persion);
    }

    @Override
    public Persion findOne(Map<String, Object> params) {
        Query query = new Query(Criteria.where("name").is(params.get("name")));
        return mongoTemplate.findOne(query, Persion.class);
    }

    @Override
    public List<Persion> findAll(Map<String, Object> params) {
        return mongoTemplate.find(new Query(Criteria.where("age").lt(params.get("age"))), Persion.class);
    }

    @Override
    public void update(Map<String, Object> params) {
        WriteResult res = mongoTemplate.upsert(new Query(Criteria.where("name").is(params.get("name"))), new Update().set("address", params.get("address")), Persion.class);
        System.out.println(res.getN());
    }

    @Override
    public void remove(Map<String, Object> params) {
        WriteResult res = mongoTemplate.remove(new Query(Criteria.where("name").is(params.get("name"))), Persion.class);
        System.out.println(res.getN());
    }

    @Override
    public List<Persion> getPagePersion(int pageNum, int pageSize) {
        Page<Persion> pageList = null;
        try {
            Query query = new Query();
            MongDataPageable pageable = new MongDataPageable();
            pageable.setPageNums(pageNum);
            pageable.setPageSizes(pageSize);
            long count = mongoTemplate.count(query, Persion.class);
            List<Persion> list = mongoTemplate.find(query.with(pageable), Persion.class);
            pageList = new PageImpl<Persion>(list, pageable, count);
        } catch (Exception e) {

        }
        return pageList.getContent();
    }
}
